package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/sessions"
)

// secret-key 用于加密会话数据
var store = sessions.NewCookieStore([]byte("K7J3h9F2vR8wQ4xN6mP1sL5tY0uI8oE3zA7bC4dV6fG9jH2kM5nX1qW3eR7tY"))

func main() {
	r := gin.Default()
	r.GET("/session/:uid", func(ctx *gin.Context) {
		uid := ctx.Param("uid")
		session, _ := store.Get(ctx.Request, "user_session")
		if session.Values["uid"] == nil {
			fmt.Println("Creating new session for uid:", uid)
			session.Values["username"] = "test" + uid
			session.Values["uid"] = uid
			session.Save(ctx.Request, ctx.Writer)
		}
		ctx.JSON(200, gin.H{"session username": session.Values["username"], "session uid": session.Values["uid"]})
	})
	r.GET("/logout", func(ctx *gin.Context) {
		session, _ := store.Get(ctx.Request, "user_session")
		for k := range session.Values {
			delete(session.Values, k)
		}
		//session.Options.MaxAge = -1 //更有做法 删除 cookie
		session.Save(ctx.Request, ctx.Writer)
		ctx.JSON(200, gin.H{"message": "logged out"})
	})
	r.Run(":8080")
}
